/* 
  Copyright (c) SilverLining 2015
  Date:    2016-1-7
  File:    ref.cpp  
  Description: 

*/

#include "stdafx.h"

namespace m
{
	ref_storage::ref_storage()
		: _Ptr(nullptr),
		_Assigned(false)
	{

	}

	ref_storage::ref_storage(object* ptr)
		: _Ptr(ptr),
		_Assigned(true)
	{

	}

	ref_storage::~ref_storage()
	{
		if (_Assigned)
		{
			if (_Ptr)
			{
				_Ptr->release();
			}
		}
	}

	ref_storage& ref_storage::operator=(ref_storage& other)
	{
		if (!_Assigned)
		{
			_Ptr = other._Ptr;
			_Assigned = true;
			other._Assigned = false;
			return *this;
		}
		throw new bad_result_exception(MONORET(FACILITY_OBJECT, ERROR_ALREADY_ASSIGNED), "Pointer reference storage in use.");
	}
	
	void ref_storage::clear()
	{
		_Ptr = nullptr;
		_Assigned = false;
	}

	void clear(wchar_t *& location)
	{
		if (location)
		{
			free(location);
			location = nullptr;
		}
	}

	wchar_t* assign(wchar_t*& location, const wchar_t* value)
	{
		if (location != value)
		{
			clear(location);
			if (value)
			{
				location = _wcsdup(value);
				if (location == nullptr)
				{
					throw std::bad_alloc();
				}
			}
		}
		return location;
	}
}